<template>
  <div class="login">
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">基因脸谱知识库</h3>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号" maxlength="11">
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          show-password
          @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          maxlength="4"
          @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="login-code">
          <el-button
            :loading="loading"
            :disabled="disabled"
            type="primary"
            class="login-code-button"
            @click="checkPhoneClick"
          >
            <span>{{
              codeTextShow === 0
                ? codeText.btntext
                : codeTextShow === 1
                ? count + codeText.countdown
                : codeText.getAgain
            }}</span>
          </el-button>
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">记住密码</el-checkbox>
      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="large" type="primary" class="w-full" @click.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
      <el-form-item class="go-reg">
        <a class="forgot" @click="handleForgetPwd">忘记密码</a>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
  import { checkPhone, getPhoneSMS } from '@/api/login';
  import Cookies from 'js-cookie';
  import { encrypt, decrypt } from '@/utils/jsencrypt';
  import { getCurrentInstance, ref, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import useUserStore from '@/store/modules/user';

  const userStore = useUserStore();
  const router = useRouter();
  const { proxy: $vm } = getCurrentInstance();

  const loginFormRef = ref(null);
  const loginForm = ref({
    username: '',
    password: '',
    rememberMe: false,
    code: '',
    uuid: '',
    loginType: '',
  });

  /* 控制验证码倒数-start */
  const codeText = ref({
    btntext: '发送验证码',
    countdown: 's后重发',
    getAgain: '重新获取',
  });

  const codeTextShow = ref(0);
  const count = ref(59);
  const disabled = ref(false);

  const loginRules = ref({
    username: [
      {
        required: true,
        trigger: 'blur',
        message: '手机号码不能为空',
      },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur',
      },
    ],
    password: [
      {
        required: true,
        trigger: 'blur',
        message: '密码不能为空',
      },
    ],
    code: [
      {
        required: true,
        trigger: 'change',
        message: '验证码不能为空',
      },
    ],
  });

  const loading = ref(false);
  const redirect = ref(undefined);

  getCookie();

  watch(
    () => /* Warn: Unknown source: $route */ $vm.$route,
    (route) => {
      redirect.value = route.query && route.query.redirect;
    },
    {
      immediate: true,
    },
  );

  function checkPhoneClick() {
    loginRules.value.code[0].required = false;
    loginFormRef.value.validate((valid) => {
      if (valid) {
        checkPhone(loginForm.value.username).then((res) => {
          getCode();
        });
      }
    });
  }

  function handleForgetPwd() {
    router.push({
      path: '/forget-pwd',
      query: {
        type: 'user',
      },
    });
  }

  function getCode() {
    // 手机号验证
    if (loginForm.value.username.length <= 1) {
      /* Warn: Unknown source: msgError */
      $vm.msgError('请输入手机号');
    } else {
      disabled.value = true;
      codeTextShow.value = 1;
      const interval = setInterval(() => {
        count.value--; // 倒计时计数自减
      }, 1000); // 每隔1秒变化一次
      setTimeout(() => {
        clearInterval(interval); // 清除定时器
        count.value = 59; // 第一轮结束后，再次点击获取，会从-1开始
        codeTextShow.value = 2; // 状态值等于2
        disabled.value = false; // 禁止按钮点击
      }, 60000);
      getPhoneSMS(loginForm.value.username).then((res) => {});
    }
  }

  function getCookie() {
    const username = Cookies.get('username');
    const password = Cookies.get('password');
    const rememberMe = Cookies.get('rememberMe');
    loginForm.value = {
      username: username === undefined ? loginForm.value.username : username,
      password: password === undefined ? loginForm.value.password : decrypt(password),
      rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
    };
  }

  function handleLogin() {
    loginFormRef.value.validate((valid) => {
      if (valid) {
        loading.value = true;
        if (loginForm.value.rememberMe) {
          Cookies.set('username', loginForm.value.username, {
            expires: 30,
          });
          Cookies.set('password', encrypt(loginForm.value.password), {
            expires: 30,
          });
          Cookies.set('rememberMe', loginForm.value.rememberMe, {
            expires: 30,
          });
        } else {
          Cookies.remove('username');
          Cookies.remove('password');
          Cookies.remove('rememberMe');
        }
        userStore
          .smsLogin(loginForm.value)
          .then(() => {
            router.push({
              path: redirect.value || '/index',
            });
          })
          .catch((_) => {
            loading.value = false;
          });
      }
    });
  }
</script>

<style rel="scss" lang="scss">
  @import './public.scss';
</style>
